package org.example.lanchain.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.lanchain.bean.KnowledgeBase;
import org.example.lanchain.bean.KnowledgeDocument;
import org.example.lanchain.bean.KnowledgeSearchResult;
import org.example.lanchain.bean.KnowledgeStats;
import org.example.lanchain.service.KnowledgeBaseService;
import org.example.lanchain.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 知识库管理控制器
 * 提供知识库文档的上传、搜索、统计等API接口
 */
@Tag(name = "知识库管理")
@RestController
@RequestMapping("/api/knowledge")
@CrossOrigin(origins = "*")
public class KnowledgeController {

    private static final Logger logger = LoggerFactory.getLogger(KnowledgeController.class);

    @Autowired
    private KnowledgeService knowledgeService;

    @Autowired
    private KnowledgeBaseService knowledgeBaseService;

    /**
     * 上传文档到知识库
     * 
     * @param file 上传的文件
     * @param knowledgeBaseId 所属知识库ID (可选)
     * @return 返回文档信息
     */
    @Operation(summary = "上传文档到知识库")
    @PostMapping("/upload")
    public ResponseEntity<KnowledgeDocument> uploadDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "knowledgeBaseId", required = false) Long knowledgeBaseId) {
        try {
            logger.info("开始上传文件: {}, 大小: {} bytes, 知识库ID: {}", file.getOriginalFilename(), file.getSize(), knowledgeBaseId);
            
            // 验证文件
            if (file.isEmpty()) {
                logger.error("上传的文件为空");
                return ResponseEntity.badRequest().build();
            }
            
            if (file.getOriginalFilename() == null || file.getOriginalFilename().trim().isEmpty()) {
                logger.error("文件名不能为空");
                return ResponseEntity.badRequest().build();
            }
            
            KnowledgeDocument document = knowledgeService.uploadDocument(file, knowledgeBaseId);
            logger.info("文件上传成功: {}, 文档ID: {}", file.getOriginalFilename(), document.getId());
            return ResponseEntity.ok(document);
        } catch (Exception e) {
            logger.error("文件上传失败: {}", file.getOriginalFilename(), e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取文档列表（可按知识库ID过滤）
     * 
     * @param knowledgeBaseId 知识库ID (可选)
     * @return 返回文档列表
     */
    @Operation(summary = "获取文档列表（可按知识库ID过滤）")
    @GetMapping("/documents")
    public ResponseEntity<List<KnowledgeDocument>> getDocuments(
            @RequestParam(value = "knowledgeBaseId", required = false) Long knowledgeBaseId) {
        try {
            List<KnowledgeDocument> documents;
            if (knowledgeBaseId != null) {
                documents = knowledgeService.getDocumentsByKnowledgeBaseId(knowledgeBaseId);
            } else {
                documents = knowledgeService.getAllDocuments();
            }
            return ResponseEntity.ok(documents);
        } catch (Exception e) {
            logger.error("获取文档列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 根据ID获取文档
     * 
     * @param id 文档ID
     * @return 返回文档信息
     */
    @Operation(summary = "获取文档详情")
    @GetMapping("/documents/{id}")
    public ResponseEntity<KnowledgeDocument> getDocumentById(@PathVariable Long id) {
        try {
            KnowledgeDocument document = knowledgeService.getDocumentById(id);
            if (document != null) {
                return ResponseEntity.ok(document);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("获取文档详情失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除文档
     * 
     * @param id 文档ID
     * @return 返回删除结果
     */
    @Operation(summary = "删除文档")
    @DeleteMapping("/documents/{id}")
    public ResponseEntity<Boolean> deleteDocument(@PathVariable Long id) {
        try {
            boolean result = knowledgeService.deleteDocument(id);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("删除文档失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 搜索知识库
     * 
     * @param query 搜索查询
     * @param maxResults 最大结果数（可选，默认10）
     * @param minScore 最小相似度（可选，默认0.8）
     * @return 返回搜索结果列表
     */
    @Operation(summary = "搜索知识库")
    @GetMapping("/search")
    public ResponseEntity<List<KnowledgeSearchResult>> searchKnowledge(
            @RequestParam String query,
            @RequestParam(defaultValue = "10") int maxResults,
            @RequestParam(defaultValue = "0.8") double minScore) {
        try {
            List<KnowledgeSearchResult> results = knowledgeService.searchKnowledge(query, maxResults, minScore);
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            logger.error("搜索知识库失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取知识库统计信息
     * 
     * @return 返回统计信息
     */
    @Operation(summary = "获取统计信息")
    @GetMapping("/stats")
    public ResponseEntity<KnowledgeStats> getKnowledgeStats() {
        try {
            KnowledgeStats stats = knowledgeService.getKnowledgeStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            logger.error("获取统计信息失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 重新处理文档（重新向量化）
     * 
     * @param id 文档ID
     * @return 返回处理结果
     */
    @Operation(summary = "重新处理文档")
    @PostMapping("/documents/{id}/reprocess")
    public ResponseEntity<Boolean> reprocessDocument(@PathVariable Long id) {
        try {
            boolean result = knowledgeService.reprocessDocument(id);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("重新处理文档失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    // KnowledgeBase 相关API

    /**
     * 创建新知识库
     * @param knowledgeBase 知识库对象
     * @return 创建后的知识库对象
     */
    @Operation(summary = "创建知识库")
    @PostMapping("/bases")
    public ResponseEntity<KnowledgeBase> createKnowledgeBase(@RequestBody KnowledgeBase knowledgeBase) {
        try {
            KnowledgeBase createdKb = knowledgeBaseService.createKnowledgeBase(knowledgeBase);
            return ResponseEntity.ok(createdKb);
        } catch (Exception e) {
            logger.error("创建知识库失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 根据ID获取知识库
     * @param id 知识库ID
     * @return 知识库对象或null
     */
    @Operation(summary = "根据ID获取知识库")
    @GetMapping("/bases/{id}")
    public ResponseEntity<KnowledgeBase> getKnowledgeBaseById(@PathVariable Long id) {
        try {
            KnowledgeBase kb = knowledgeBaseService.getKnowledgeBaseById(id);
            if (kb != null) {
                return ResponseEntity.ok(kb);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("获取知识库失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取所有知识库
     * @return 知识库列表
     */
    @Operation(summary = "获取所有知识库")
    @GetMapping("/bases")
    public ResponseEntity<List<KnowledgeBase>> getAllKnowledgeBases() {
        try {
            List<KnowledgeBase> kbs = knowledgeBaseService.getAllKnowledgeBases();
            return ResponseEntity.ok(kbs);
        } catch (Exception e) {
            logger.error("获取所有知识库失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 根据用户ID获取知识库列表
     * @param userId 用户ID
     * @return 知识库列表
     */
    @Operation(summary = "根据用户ID获取知识库列表")
    @GetMapping("/bases/user/{userId}")
    public ResponseEntity<List<KnowledgeBase>> getKnowledgeBasesByUserId(@PathVariable Long userId) {
        try {
            List<KnowledgeBase> kbs = knowledgeBaseService.getKnowledgeBasesByUserId(userId);
            return ResponseEntity.ok(kbs);
        } catch (Exception e) {
            logger.error("根据用户ID获取知识库失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 更新知识库
     * @param id 知识库ID
     * @param knowledgeBase 知识库对象
     * @return 更新是否成功
     */
    @Operation(summary = "更新知识库")
    @PutMapping("/bases/{id}")
    public ResponseEntity<Boolean> updateKnowledgeBase(@PathVariable Long id, @RequestBody KnowledgeBase knowledgeBase) {
        try {
            knowledgeBase.setId(id);
            boolean result = knowledgeBaseService.updateKnowledgeBase(knowledgeBase);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("更新知识库失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除知识库
     * @param id 知识库ID
     * @return 删除是否成功
     */
    @Operation(summary = "删除知识库")
    @DeleteMapping("/bases/{id}")
    public ResponseEntity<Boolean> deleteKnowledgeBase(@PathVariable Long id) {
        try {
            boolean result = knowledgeBaseService.deleteKnowledgeBase(id);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("删除知识库失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
} 